package com.gzhryc.weixin.gzh;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.Charset;

import com.gzhryc.common.json.JsonTools;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.gzhryc.weixin.api.DefaultApiResponse;
import com.gzhryc.weixin.gzh.models.AccessToken;
import com.gzhryc.weixin.gzh.msg.CreateBarcodeRequest;
import com.gzhryc.weixin.gzh.msg.CreateBarcodeResponse;

public class WxBarcodeApi extends AbsWeixinApi{

	private final static Logger log = Logger.getLogger(WxBarcodeApi.class);
	
	public WxBarcodeApi(AccessToken accessToken) {
		super(accessToken);
	}
	
	/**
	 * 创建临时的二维码
	 * @param val
	 * @param time
	 * @return
	 */
	public CreateBarcodeResponse createTemporaryBarcode(Integer val,Long time){
		CreateBarcodeRequest request = new CreateBarcodeRequest();
		request.setAction_name(CreateBarcodeRequest.ACTION_NAME_1);
		request.setExpire_seconds(time);
		request.setAction_info(new CreateBarcodeRequest.ActionInfo());
		CreateBarcodeRequest.SceneId sceneId = new CreateBarcodeRequest.SceneId();
		sceneId.setScene_id(val);
		request.getAction_info().setScene(sceneId);
		
		return createBarcode(request);
	}
	
	/**
	 * 创建永久性二维码
	 * @param val
	 * @return
	 */
	public CreateBarcodeResponse createLongBarcode(Integer val){
		CreateBarcodeRequest request = new CreateBarcodeRequest();
		request.setAction_name(CreateBarcodeRequest.ACTION_NAME_2);
		request.setAction_info(new CreateBarcodeRequest.ActionInfo());
		CreateBarcodeRequest.SceneId sceneId = new CreateBarcodeRequest.SceneId();
		sceneId.setScene_id(val);
		request.getAction_info().setScene(sceneId);
		
		return createBarcode(request);
	}
	
	/**
	 * 创建永久性二维码
	 * @param val
	 * @return
	 */
	public CreateBarcodeResponse createLongBarcode(String val){
		CreateBarcodeRequest request = new CreateBarcodeRequest();
		request.setAction_name(CreateBarcodeRequest.ACTION_NAME_3);
		request.setAction_info(new CreateBarcodeRequest.ActionInfo());
		CreateBarcodeRequest.SceneStr sceneStr = new CreateBarcodeRequest.SceneStr();
		sceneStr.setScene_str(val);
		request.getAction_info().setScene(sceneStr);
		
		return createBarcode(request);
	}
	
	public CreateBarcodeResponse createBarcode(CreateBarcodeRequest request){
		CloseableHttpResponse response = null;
		try {
			CloseableHttpClient httpclient = HttpClients.createDefault();

			URI uri = new URIBuilder()
		        .setScheme("https")
		        .setHost("api.weixin.qq.com")
		        .setPath("/cgi-bin/qrcode/create")
		        .setParameter("access_token",accessToken.getAccess_token())
		        .build();
			
			StringEntity strEntity = new StringEntity(JsonTools.toJson(request),
			        ContentType.create("application/json", Consts.UTF_8));
			
			HttpPost httppost = new HttpPost(uri);
			httppost.setEntity(strEntity);
			
			response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			if(entity != null){
				String str = EntityUtils.toString(entity,Charset.forName("UTF-8"));
				if(isError(str)){
					accessToken.queuePut(JsonTools.fromJson(str, DefaultApiResponse.class));
				}else{
					return JsonTools.fromJson(str,CreateBarcodeResponse.class);
				}
			}
		} catch(Exception e){
			log.error(e);
		} finally {
			if(response != null){
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return null;
	}
	
	/**
	 * 获取图片路径
	 * @param ticket
	 * @return
	 */
	public String getImgUrl(String ticket){
		try {
			ticket = URLEncoder.encode(ticket, "UTF-8");
			return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+ticket;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

}
